﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 实验2_控件遍历
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public TreeView TV
        {
            get;
            set;
        }
        // 加载窗口时调用函数，
        private void Form2_Load(object sender, EventArgs e)
        {
            if (TV != null)
            {
                TV.Nodes.Clear();
                TreeNode tnRoot = new TreeNode(this.Name);
                // TV即主窗口中的treeView1
                TV.Nodes.Add(tnRoot);
                // 调用函数将所有控件加入到子节点
                RecursiveControls(this, tnRoot);
                // 自动展开所有树节点
                TV.ExpandAll();
            }
        }
        // 遍历控件
        void RecursiveControls(Control ctlParent, TreeNode tnParent)
        {
            foreach (Control ctl in ctlParent.Controls)
            {
                
                TreeNode tn = new TreeNode(ctl.Name);
                // tn.Tag指向当前控件ctl，结点要与控件对应
                tn.Tag = ctl;
                tnParent.Nodes.Add(tn);
                // 如果是MenuStrip，将菜单项加入到节点中
                if (ctl is MenuStrip)
                {
                    GetMenu((ctl as MenuStrip), tn);
                }
                // 递归
                RecursiveControls(ctl, tn);
            }
        }
        // 获取菜单项
        void GetMenu(MenuStrip MenuS, TreeNode tnParent)
        {
            for (int i = 0; i < MenuS.Items.Count; i++) //遍历MenuStrip组件中的一级菜单项
            {
                TreeNode tn = new TreeNode(MenuS.Items[i].Text);
                tn.Tag = MenuS.Items[i];
                tnParent.Nodes.Add(tn);
                RecursiveMenu(MenuS.Items[i], tn);  // 调用函数，遍历二级菜单
            }
        }
        // 递归添加子菜单项
        private void RecursiveMenu(ToolStripItem toolStripItem, TreeNode tnParent)
        {
            ToolStripDropDownItem newmenu = (ToolStripDropDownItem)toolStripItem;
            if (newmenu.HasDropDownItems && newmenu.DropDownItems.Count > 0)
            {
                for (int i = 0; i < newmenu.DropDownItems.Count; i++)   // 遍历下一级菜单
                {
                    TreeNode tn = tnParent.Nodes.Add(newmenu.DropDownItems[i].Text);
                    tn.Tag = newmenu.DropDownItems[i];
                    RecursiveMenu(newmenu.DropDownItems[i], tn);
                }
            }
        }
        // 关闭窗口前调用函数，清空树节点
        private void Form2_Close(object sender, FormClosingEventArgs e)
        {
            if (TV != null)
            {
                TV.Nodes.Clear();
            }
        }

    }
}
